package com.teaut.dota.hider.entity.common;

import com.teaut.dota.hider.boot.SnowFlakeComponent;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;
import org.springframework.util.StringUtils;

import java.io.Serializable;

/**
 * JPA 雪花算法ID生成器
 */
public class SnowFlakeIdGenerator implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object eneity) throws HibernateException {
        if (eneity instanceof AbstractBaseEntity && StringUtils.hasText(((AbstractBaseEntity) eneity).getId())) {
            return ((AbstractBaseEntity) eneity).getId();
        }else {
            return SnowFlakeComponent.getBean().nextIdString();
        }
    }
}